package com.base.myproject.client.HR.Books;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.base.myproject.client.busi.BaseStore;
import com.base.myproject.client.busi.BO.BaseObject;
import com.base.myproject.client.busi.BO.BusiObject;
import com.base.myproject.client.busi.print.PrintBcodeDialog;
import com.base.myproject.client.jdbc.DataSet;
import com.base.myproject.client.jdbc.StoreInfo;
import com.base.myproject.client.tools.CommandSyncContainer;
import com.base.myproject.client.tools.CommandSyncReturnObject;
import com.base.myproject.client.tools.CommandSyncsql;
import com.base.myproject.client.tools.GreetingService;
import com.base.myproject.client.tools.GreetingServiceAsync;
import com.base.myproject.client.ui.BaseFormPanel;
import com.base.myproject.client.ui.BaseGrid;
import com.base.myproject.client.ui.BaseJDBCPanel;
import com.base.myproject.client.ui.celleditor.BaseComboBoxForm;
import com.extjs.gxt.ui.client.GXT;
import com.extjs.gxt.ui.client.Style.HorizontalAlignment;
import com.extjs.gxt.ui.client.Style.Orientation;
import com.extjs.gxt.ui.client.Style.SelectionMode;
import com.extjs.gxt.ui.client.Style.VerticalAlignment;
import com.extjs.gxt.ui.client.data.ModelType;
import com.extjs.gxt.ui.client.event.BaseEvent;
import com.extjs.gxt.ui.client.event.ButtonEvent;
import com.extjs.gxt.ui.client.event.ComponentEvent;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.event.MessageBoxEvent;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.widget.ContentPanel;
import com.extjs.gxt.ui.client.widget.Dialog;
import com.extjs.gxt.ui.client.widget.HorizontalPanel;
import com.extjs.gxt.ui.client.widget.Info;
import com.extjs.gxt.ui.client.widget.Label;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.form.CheckBox;
import com.extjs.gxt.ui.client.widget.form.DateField;
import com.extjs.gxt.ui.client.widget.form.FieldSet;
import com.extjs.gxt.ui.client.widget.form.TextField;
import com.extjs.gxt.ui.client.widget.grid.CheckBoxSelectionModel;
import com.extjs.gxt.ui.client.widget.grid.ColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.ColumnModel;
import com.extjs.gxt.ui.client.widget.layout.RowLayout;
import com.extjs.gxt.ui.client.widget.layout.TableData;
import com.extjs.gxt.ui.client.widget.layout.TableLayout;
import com.extjs.gxt.ui.client.widget.toolbar.PagingToolBar;
import com.google.gwt.core.client.GWT;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.i18n.client.NumberFormat;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.VerticalPanel;

public class B_r_books extends BaseJDBCPanel{
	Button to_return  = new Button ("还书");
	Button cif_out  = new Button ("借书");
	Button search  = new Button ("查询");
	FieldSet fs = new FieldSet();//借书
	FieldSet fs1 = new FieldSet();//还书
	FieldSet fs2 = new FieldSet();//查询
	String sql = "select * from hr_borrow where 1=1 and backDate is null order by brwDate asc";
	PagingToolBar toolBar1 = null;
	DateField date = new DateField();
	Date serverDate;  //服务器的时间
	Dialog finesBox = new Dialog();
	CheckBox searchAll = new CheckBox();
	
	String bcode;  //借还书的员工号
	long icode;  //还书的借书记录的ICODE
	
	DateTimeFormat format = DateTimeFormat
	.getFormat("yyyy-MM-dd");
	
	Label OverdueDays = new Label("该员工逾期X天\t");
	TextField<String> finesNum = new TextField<String>();
	
	public B_r_books(){
		init();
	}
	
	public B_r_books(String sql) {
		searchAll.setEnabled(false);
		sql = sql.replaceAll("count.*num", "*"); // 将传过来的查询个数的SQL语句改成查询所有在查询范围内的过期图书
		this.sql = sql + " order by brwDate asc";  //显示的话都只以借入日期ASC，查询就会用DESC
		init();
	}
	
	public void init(){
		finesBox.setButtons(Dialog.OKCANCEL);
		finesBox.setBodyStyleName("pad-text");  
		finesBox.setHideOnButtonClick(true); 
		finesBox.getButtonById(Dialog.OK).setText("确定");
		finesBox.getButtonById(Dialog.CANCEL).setText("打印");
		finesBox.setWidth(200);  
		finesBox.setHeight(100);
		finesBox.setLayout(new RowLayout(Orientation.HORIZONTAL));
		finesBox.setHeading("确认罚款金额");
		finesBox.add(OverdueDays);
		finesNum.setWidth(30);
		finesBox.add(finesNum);
		finesBox.add(new Label("\t元"));
		
		finesBox.getButtonById(Dialog.OK).addSelectionListener(new SelectionListener<ButtonEvent>(){

			@Override
			public void componentSelected(ButtonEvent ce) {
				insertFines();
			}
		});
		
		finesBox.getButtonById(Dialog.CANCEL).addSelectionListener(new SelectionListener<ButtonEvent>(){

			@Override
			public void componentSelected(ButtonEvent ce) {
				insertFines(1);
			}
		});
		
		//得到数据库报务器的时间
		String getDate = "select getdate() as date";
		final GreetingServiceAsync greetingService = GWT
				.create(com.base.myproject.client.tools.GreetingService.class);
		greetingService.getDataSet(getDate, new AsyncCallback<DataSet>() {
			@Override
			public void onFailure(Throwable caught) {
			}

			@Override
			public void onSuccess(DataSet result) {
				String dateStr = result.getValue(0, "date");
				dateStr = dateStr.substring(0, 10);
				serverDate = format.parse(dateStr);
				C_data5.setValue(serverDate);
				date.setValue(serverDate);
				}
		});
		
		initwidget();
		registerMainStore(store);
		registerStore(store);
	}
	
	private void initwidget() {
		toolBar1 = new PagingToolBar(20);
		
		to_return.addListener(Events.OnClick, getListener());
		cif_out.addListener(Events.OnClick, getListener());
		C_data5.addListener(Events.Change, getListener());
		date.addListener(Events.Change, getListener());
		search.addListener(Events.OnClick, getListener());
		
		fs.setHeading("借书操作");
		fs.add(getBaseFormPanel());
		
		fs1.setHeading("还书操作");
		fs1.add(getReturnFormPanel());
		
		HorizontalPanel hp = new HorizontalPanel();
		hp.setSpacing(3);
		hp.add(fs);
		hp.add(fs1);
		
		fs2.setHeading("查询操作");
		fs2.add(getSearchFormPanel());
		
		ContentPanel panel2 = new ContentPanel();
		panel2.setHeaderVisible(false);
		panel2.setBodyBorder(false);
		panel2.add(getgrid());
		panel2.setBottomComponent(toolBar1);
		
		VerticalPanel vp=new VerticalPanel();
		vp.setSpacing(3);
		vp.add(hp);
		vp.add(fs2);
		vp.add(panel2);
		
		
		add(vp);
		
	}
	/***/
	BaseStore<BusiObject> store = null;

	BaseStore<BusiObject> getStore() {
		if (store == null) {
			createStore();
		}
		return store;
	}
	
	BaseStore<BusiObject> createStore() {
		ModelType type = new ModelType();
		type.setRoot("records");
		type.setRecordName("record");
		type.setTotalName("totle");
		type.addField("icode");
		type.getField("icode").setType(Long.class);
		type.addField("bcode");
		type.getField("bcode").setType(String.class);
		type.addField("bookNo");
		type.getField("bookNo").setType(String.class);
		type.addField("brwDate");
		type.getField("brwDate").setType(Date.class);
		type.addField("backDate");
		type.getField("backDate").setType(Date.class);
		type.addField("isbreak");
		type.getField("isbreak").setType(String.class);
		type.addField("fines");
		type.getField("fines").setType(Integer.class);
		StoreInfo info = new StoreInfo();
		info.setTablename("hr_borrow");
		info.setKeyname(new String[] { "icode" });
		info.setSql(sql);
		store = new BaseStore<BusiObject>(type, info);
		store.setToolBar(toolBar1);
		return store;
	}
	/***/
	BaseGrid<BaseObject> grid=null;

	BaseGrid<BaseObject> getgrid() {
		if (grid == null) {
			createGrid();
		}
		return grid;
	}
	
	BaseGrid<BaseObject> createGrid() {
		CheckBoxSelectionModel cbs = new CheckBoxSelectionModel();
		List<ColumnConfig> columns = new ArrayList<ColumnConfig>();
		columns.add(cbs.getColumn());

		ColumnConfig C2 = new ColumnConfig("bcode", "员工姓名", 80);
		C2.setRenderer(gridBcode);
		columns.add(C2);

		ColumnConfig C3 = new ColumnConfig("bookNo", "图书名称", 250);
		C3.setRenderer(bookRenderer);
		columns.add(C3);
		ColumnConfig C5 = new ColumnConfig("brwDate", "借出日期", 120);
		C5.setDateTimeFormat(DateTimeFormat.getFormat("yyyy-MM-dd"));
		columns.add(C5);
		ColumnConfig C7 = new ColumnConfig("backDate", "实际归还日期", 120);
		C7.setDateTimeFormat(DateTimeFormat.getFormat("yyyy-MM-dd"));
		columns.add(C7);
		ColumnConfig C8 = new ColumnConfig("isbreak", "是否损坏", 80);
		columns.add(C8);
		ColumnConfig C9 = new ColumnConfig("fines", "逾期罚款", 80);
		C9.setNumberFormat(NumberFormat.getFormat("##"));
		columns.add(C9);

		ColumnModel cm = new ColumnModel(columns);
		grid = new BaseGrid<BaseObject>(getStore(), cm, false, false);
		cbs.setSelectionMode(SelectionMode.SINGLE);
		grid.setSelectionModel(cbs);
		grid.setHeight(250);
		grid.setWidth(950);
		grid.getStore().reload(); // 暂时先用reload，因为不reload的话，分面不出来效果，但是这样数据多了会慢。再想解决方法
		return grid;
	}
	/****/
	BaseFormPanel form = null;

	BaseFormPanel getBaseFormPanel() {
		if (form == null) {
			createForm();
		}
		return form;
	}

	BaseComboBoxForm<BaseObject> gridBcode = new BaseComboBoxForm<BaseObject>("a.bcode", "a.bname", "bcode a, bcode_job b", " where a.bcode = b.bcode and b.employstatus='在职'", true);
	BaseComboBoxForm<BaseObject> borrowBcode = new BaseComboBoxForm<BaseObject>("a.bcode", "b.employno %2B a.bname", "bcode a, bcode_job b", " where a.bcode = b.bcode and b.employstatus='在职' and not exists (select * from hr_borrow where bcode = a.bcode and backdate is null)", true);
	
	//查出所有“正常”的图书，因为只有“正常”的图书才能外借
	BaseComboBoxForm<BaseObject> book = new BaseComboBoxForm<BaseObject>("bookNo", "bookNo %2B bookName", "hr_book", " where status = '正常' and isbreak != '损坏'", true);
	//渲染，查询所有的图书，用于显示图书，以编号和名称显示
	BaseComboBoxForm<BaseObject> bookRenderer = new BaseComboBoxForm<BaseObject>("bookNo", "bookNo %2B bookName", "hr_book", "", true);
	
	DateField C_data5 = new DateField();
	DateField C_data6;
	Label mesg = new Label(); 
	BaseStore<BusiObject> nullStore = new BaseStore<BusiObject>();

	void createForm() {
		form = new BaseFormPanel(nullStore, false);
		form.setBodyBorder(false);
		TableLayout tl = new TableLayout(8);
		TableData td = new TableData();
		td.setRowspan(1);
		td.setHorizontalAlign(HorizontalAlignment.LEFT);
		td.setVerticalAlign(VerticalAlignment.TOP);
		td.setPadding(2);
		form.setLayout(tl);
		form.setHeaderVisible(false);

		form.add(new Label("员工编号:"), td);
		borrowBcode.setWidth(120);
		form.add(borrowBcode, td);

		form.add(new Label("图书编号:"), td);
		book.setWidth(250);
		form.add(book, td);

		form.add(new Label("借书日期:"), td);
		C_data5.setWidth(100);
		C_data5.getPropertyEditor().setFormat(
				DateTimeFormat.getFormat("yyyy-MM-dd"));
		form.add(C_data5, td);

		form.add(cif_out, td);
		form.inited();
	}
	
	BaseFormPanel returnForm = null;

	BaseFormPanel getReturnFormPanel() {
		if (returnForm == null) {
			createReturnForm();
		}
		return returnForm;
	}

	void createReturnForm() {
		returnForm = new BaseFormPanel(nullStore, false);
		returnForm.setBodyBorder(false);
		TableLayout tl = new TableLayout(8);
		TableData td = new TableData();
		td.setRowspan(1);
		td.setHorizontalAlign(HorizontalAlignment.LEFT);
		td.setVerticalAlign(VerticalAlignment.TOP);
		td.setPadding(2);
		returnForm.setLayout(tl);
		returnForm.setHeaderVisible(false);

		returnForm.add(new Label("归还日期:"), td);
		date.setWidth(100);
		date.getPropertyEditor().setFormat(
				DateTimeFormat.getFormat("yyyy-MM-dd"));
		returnForm.add(date, td);
		returnForm.add(to_return, td);
		returnForm.inited();
	}
	
	BaseFormPanel searchForm = null;

	BaseFormPanel getSearchFormPanel() {
		if (searchForm == null) {
			createSearchForm();
		}
		return searchForm;
	}

	//只显示有借书记录的员工
	BaseComboBoxForm<BaseObject> searchBcode = new BaseComboBoxForm<BaseObject>("a.bcode", "b.employno %2B a.bname", "bcode a, bcode_job b", " where a.bcode = b.bcode and exists (select * from hr_borrow where bcode = a.bcode and backdate is null)", true);
	
	//只提供所有已经借出还没归还的图书进行查询
	BaseComboBoxForm<BaseObject> searchBook = new BaseComboBoxForm<BaseObject>("bookNo", "bookNo %2B bookName", "hr_book", " where status = '借出'", true);
	DateField lentStart = new DateField();
	DateField lentEnd = new DateField();
	
	void createSearchForm() {
		searchForm = new BaseFormPanel(nullStore, false);
		searchForm.setBodyBorder(false);
		TableLayout tl = new TableLayout(11);
		TableData td = new TableData();
		td.setRowspan(1);
		td.setHorizontalAlign(HorizontalAlignment.LEFT);
		td.setVerticalAlign(VerticalAlignment.TOP);
		td.setPadding(2);
		searchForm.setLayout(tl);
		searchForm.setHeaderVisible(false);

		searchForm.add(new Label("员工编号:"), td);
		searchBcode.setWidth(120);
		searchForm.add(searchBcode, td);

		searchForm.add(new Label("图书编号:"), td);
		searchBook.setWidth(250);
		searchForm.add(searchBook, td);

		searchForm.add(new Label("借出日期从:"), td);
		lentStart.setWidth(100);
		lentStart.getPropertyEditor().setFormat(
				DateTimeFormat.getFormat("yyyy-MM-dd"));
		searchForm.add(lentStart, td);
		
		searchForm.add(new Label("到:"), td);
		lentEnd.setWidth(100);
		lentEnd.getPropertyEditor().setFormat(
				DateTimeFormat.getFormat("yyyy-MM-dd"));
		searchForm.add(lentEnd, td);
		
		searchForm.add(new Label("显示所有信息:"), td);
		searchForm.add(searchAll, td);
		searchForm.add(search, td);
		searchForm.inited();
	}
			
	int sync = 0;
	Listener<BaseEvent> defaultlistener;
	CommandSyncsql csql = new CommandSyncsql();
	String returnBookSql = "";  //还书记录的UPDATE语句

	Listener<BaseEvent> getListener() {
		if (defaultlistener != null) {
			return defaultlistener;
		}
		defaultlistener = new Listener<BaseEvent>() {
			public void handleEvent(BaseEvent be) {
				sync++;
				try {
					if (sync == 1) {
						if (be.getType() == Events.Select) {
							
						} else if (be.getType() == Events.OnClick) {
							if (be.getSource().equals(to_return)) {
								final BaseObject model = grid.getSelectionModel().getSelectedItem();
								if (model == null) {
									MessageBox.alert("提示", "请选中要归还的图书再按归还按钮，谢谢", null);
									return;
								}
								
								icode = model.get("icode"); 
								bcode = model.get("bcode");
								Date lastDate = model.get("brwDate");
								if (date.getValue().before(lastDate)) {
									MessageBox.alert("提示", "归还图书日期必须大于借书日期，谢谢", null);
									return;
								}
								MessageBox
								.confirm(
										"存档", "请确认图书是否完整归还？如果完整归还请选择“是”，损坏请选择“否”，谢谢",
										new Listener<MessageBoxEvent>() {
											public void handleEvent(final MessageBoxEvent be) {
												final String dateStr = date.getRawValue().equals("") ? "getdate()" : "'" + date.getRawValue() + "'";
												
												//这条SQL用于查出该员工归还这批书中总共的罚款为多少钱
												String finesSql = "select case when datediff(d,lastDate," + dateStr + ") >=0 then " +
														"datediff(d,lastDate," + dateStr + ") else 0 end as finesDate, case when datediff(d,lastDate," + dateStr + ") >=0 then " +
														"datediff(d,lastDate," + dateStr + ") else 0 end * cast((select name from dictionary where type = 'book' and code = 'fines') as int) as fines, backDate from hr_borrow where icode = " + 
														icode + "";
												
												final com.base.myproject.client.tools.GreetingServiceAsync greetingService2 = GWT
												.create(com.base.myproject.client.tools.GreetingService.class);
										greetingService2.getDataSet(finesSql,
												new AsyncCallback<DataSet>() {
													@Override
													public void onFailure(
															Throwable caught) {
													}

													@Override
													public void onSuccess(DataSet result) {
														String fines = result.getValue(0, "fines");
														String finesDate = result.getValue(0, "finesDate");
														String bookSql = "";
														String bookNo = model.get("bookNo");
														
														if (result.getValue(0, "backDate") != null) {
															MessageBox.alert("提示", "该书已经归还，不需要再归还，谢谢", null);
															return;
														}
														
														//根据图书是否损坏，构建两条不同的SQL语句，用来更新对应的hr_borrow表和hr_book表
														if (be.getButtonClicked().getText().equals(
																		GXT.MESSAGES.messageBox_yes())) {
															returnBookSql = "update hr_borrow set backDate = " + dateStr + ", fines = " + fines + " where icode = " + icode;
															bookSql = "update hr_book set status = '正常' where bookNo = '" + bookNo + "'";
														} else {
															returnBookSql = "update hr_borrow set backDate = " + dateStr + ", isbreak = '损坏', fines = " + fines + " where icode = " + icode;
															bookSql = "update hr_book set status = '正常', isbreak = '损坏' where bookNo = '" + bookNo + "'";
														}
														csql.getV().add(bookSql);
														
														//是否需要罚款，如果需要则要生成一条罚款记录到津贴表中，并且更新之前的还书的UPDATE语句
														//不需要的话就直接向服务器发送SQL
														if (!fines.equals("0")) {
															OverdueDays.setText("该员工逾期" + finesDate + "天，应扣款\t");
															finesNum.setValue(fines);
															finesBox.show();
														} else {
															csql.getV().add(returnBookSql);
															Separation(csql);
														}
													}
												});
											}
										});
								
								/*
								 * 这是一个人同时归还多本书的实现，现在规定一人只能借一本，所以不会存在一人同时还多本书的情况
								 * final List<BaseObject> selectModelList = grid.getSelectionModel().getSelectedItems();
								if (selectModelList.size() == 0) {
									MessageBox.alert("提示", "请选中要归还的图书再按归还按钮，谢谢", null);
									return;
								}
								
								String bcode = "";  //保存还书员工的编号，用来判断是否是多人还书，如果是多人还书是不允许的
								List<BaseObject> listModelList = new ArrayList<BaseObject>(selectModelList);
								//判断这批要归还的图书中是否有已经归还了的，归还的把它从list中删除
								for (int i=0; i < selectModelList.size(); i++) {
									
									BaseObject selectModel = selectModelList.get(i);
									if (selectModel.get("backDate") != null) {
										listModelList.remove(selectModel);
									}
									
									if (i == 0) {
										bcode = selectModel.get("bcode");
									} else {
										if (!bcode.equals(selectModel.get("bcode"))) {
											MessageBox.alert("提示", "你选中的借书记录中包含多个员工的借书记录，每次只能对一个员工进行归还图书，请重新选择，谢谢", null);
											return;
										}
									}
								}
								
								if (listModelList.size() == 0) {
									MessageBox.alert("提示", "你选中的图书都已经归还了，不需要再归还，谢谢", null);
									return;
								}
								
								//询问这批书是否已经损坏，如果损坏就把书标记为损坏了的书（每一批只能询问一次，也就是说一选损坏，所有都坏了）
								MessageBox
								.confirm(
										"存档", "图书是否损坏？如果损坏请按‘是’，系统将该书标记为损坏，谢谢",
										new Listener<MessageBoxEvent>() {
											public void handleEvent(MessageBoxEvent be) {
												String icodeList = "(";
												String bookNoList = "(";
												for (BaseObject selectModel : selectModelList) {
													icodeList += selectModel.get("icode") + ",";
													bookNoList += "'" + selectModel.get("bookNo") + "',";
												}
												
												icodeList = icodeList.substring(0, icodeList.length() -1) + ")";
												bookNoList = bookNoList.substring(0, bookNoList.length() -1) + ")";
												
												String bookSql = "";
												String returnBookSql = "";
												String dateStr = date.getRawValue().equals("") ? "getdate()" : "'" + date.getRawValue() + "'";
												
												//这条SQL用于查出该员工归还这批书中总共的罚款为多少钱（1天两块）
												String finesSql = "select sum(case when datediff(d,lastDate," + dateStr + ") >=0 then " +
														"datediff(d,lastDate," + dateStr + ") else 0 end) * 2 as fines from hr_borrow where icode in " + 
														icodeList + " group by bcode";
												
												final com.base.myproject.client.tools.GreetingServiceAsync greetingService2 = GWT
												.create(com.base.myproject.client.tools.GreetingService.class);
										greetingService2.getDataSet(finesSql,
												new AsyncCallback<DataSet>() {
													@Override
													public void onFailure(
															Throwable caught) {
													}

													@Override
													public void onSuccess(DataSet result) {
														String fines = result.getValue(0, "fines");
														if (!fines.equals("0")) {
															MessageBox.alert("提示", "该员工这次还书逾期，需要交" + fines + "块钱罚金", null);
														}
													}
												});
												
												//根据图书是否损坏，构建两条不同的SQL语句，用来更新对应的hr_borrow表和hr_book表
												if (be.getButtonClicked().getText().equals(
																GXT.MESSAGES.messageBox_yes())) {
													returnBookSql = "update hr_borrow set backDate = " + dateStr + ", isbreak = '损坏', fines = (case when datediff(d,lastDate, " + 
													dateStr + ") > 0 then datediff(d, lastDate, " + dateStr + ") else 0 end * 2) where icode in " + icodeList;
													bookSql = "update hr_book set status = '', isbreak = '损坏' where bookNo in " + bookNoList;
												} else {
													returnBookSql = "update hr_borrow set backDate = " + dateStr + ", fines = (case when datediff(d,lastDate, " + 
													dateStr + ") > 0 then datediff(d, lastDate, " + dateStr + ") else 0 end * 2) where icode in " + icodeList;
													bookSql = "update hr_book set status = '' where bookNo in " + bookNoList;
												}
												
												csql.getV().add(returnBookSql);
												csql.getV().add(bookSql);
												Separation("", icodeList, csql);
											}
										});*/
							} else if (be.getSource().equals(cif_out)) {
								final String date = C_data5.getRawValue().equals("") ? "getdate()" : "'" + C_data5.getRawValue() + "'";// 借出日期
								if (borrowBcode.getValue() == null || book.getValue() == null) {
									MessageBox.alert("警告", "请确定该借书记录的信息是否完整!",
											null);
									return;
								}
								
								bcode = borrowBcode.getValue().get("code");// 借书的员工编号
								final String bookNo = book.getValue().get("code");
								
								//查出这本书的最后还书日期、书的状态、员工借书的最后提醒日期、最后提醒日期是否大于最后还书日期和借书日期与最后还书
								//日期的差值（因为小于15天要给出提醒）
								String getBookDeadline = "select status,returnDate,case when returnDate >= dateadd(d," +
										"cast((select name from dictionary where type = 'book' and code = 'employeesDeadline')" +
										" as int)," + date + ") then '1' else '0' end as isBeyond," +
										"dateadd(d,cast((select name from dictionary where type = 'book' and " +
										"code = 'employeesDeadline') as int)," + date + ") as maxDate,datediff(d," + 
										date + ",returnDate) actualDateNum from hr_book where bookNo = '" + bookNo + "'";
								final com.base.myproject.client.tools.GreetingServiceAsync greetingService2 = GWT
										.create(com.base.myproject.client.tools.GreetingService.class);
								greetingService2.getDataSet(getBookDeadline,
										new AsyncCallback<DataSet>() {
											@Override
											public void onFailure(
													Throwable caught) {
											}

											@Override
											public void onSuccess(DataSet result) {
												String lastDate = "";
												
												/*
												 * 根据图书的最后归还日期，判断员工借书的还书期限超过了图书的最后还书日期，就将员工的最后还书日期也设置为
												 * 应该归还图书的最后一天
												 * if (result.getValue(0, "isBeyond").equals("1")) {
													lastDate = result.getValue(0, "maxDate");
												} else {
													MessageBox.alert("提示", "该书还有" + result.getValue(0, "actualDateNum") + "天就到期，最后还书日期为" + result.getValue(0, "returnDate").substring(0, 10), null);
													lastDate = result.getValue(0, "returnDate");
												}*/
												String returnDate = result.getValue(0, "returnDate").substring(0, 10);
												
												//书已经到期或快到期的，要提醒用户的，到期的将不能外借，如果快到期的就只给提醒，同时还能外借
												if (result.getValue(0, "isBeyond").equals("0")) {
													int distanceBookExpireDate = Integer.parseInt(result.getValue(0, "actualDateNum"));
													if (distanceBookExpireDate <= 0) {
														MessageBox.alert("提示", "该书还有已经到期，到期日期为" + returnDate + "，所以不能再外借，请借其它书", null);
														return;
													} else {
														MessageBox.alert("提示", "该书还有" + result.getValue(0, "actualDateNum") + "天就到期，最后还书日期为" + returnDate, null);
													}
												}
												lastDate = result.getValue(0, "maxDate");
												
												String sql = "update hr_book set status='借出' where bookNo='"
														+ bookNo + "'";
												String sql2 = "insert into hr_borrow (bcode,bookNo,brwDate,lastDate) "
														+ "values ('"
														+ bcode
														+ "','"
														+ bookNo
														+ "',"
														+ date 
														+ ",'" 
														+ lastDate
														+ "')";
												csql.getV().add(sql);
												csql.getV().add(sql2);
												Separation(csql);
											}
										});
							} else {
								String dateStart = lentStart.getRawValue();// 借出日期开始
								String dateEnd = lentEnd.getRawValue();// 借出日期结束
								String bcode = "";// 借书的员工编号
								String bookNo = "";
								
								if (searchBcode.getValue() != null) {
									bcode = searchBcode.getValue().get("code");
								}
								if (searchBook.getValue() != null) {
									bookNo = searchBook.getValue().get("code");
								}
								String searchSql = sql.substring(0, sql.length() - 21);
								
								if (!bcode.equals("")) {
									searchSql += " and bcode = '" + bcode + "'";
								}
								if (!bookNo.equals("")) {
									searchSql += " and bookNo = '" + bookNo + "'";
								}
								if (!dateStart.equals("")) {
									searchSql += " and brwDate >= '" + dateStart + "'";
								}
								if (!dateEnd.equals("")) {
									searchSql += " and brwDate <= '" + dateEnd + "'";
								}
								if (searchAll.getValue() == true) {
									searchSql = searchSql.replace(" and backDate is null", "");
								}
								
								searchSql += " order by brwDate desc";  //查询的话进行DESC
								grid.getStore().getStoreinfo().setSql(searchSql);
								grid.getStore().reload();
							}
							
						} else if (be.getType() == Events.Change) {
							if (be.getSource().equals(C_data5)) {
								if (C_data5.getValue() != null 
										&& C_data5.getValue().before(serverDate)) {
									MessageBox.alert("提示", "借书日期不能小于今天，请重新选择借书日期，谢谢", null);
									C_data5.setValue(null);
									return;
								}
							} else {
								if (date.getValue() != null && date.getValue().before(serverDate)) {
									MessageBox.alert("提示", "还书日期不能小于今天，请重新选择借书日期，谢谢", null);
									date.setValue(null);
									return;
								}
							}
						} else if (be.getType() == Events.KeyUp) {
							if (be instanceof ComponentEvent) {
								if (((ComponentEvent) be).getKeyCode() == 13) // 回车
								{
								}
							}
						}
					}
				} finally {
					sync--;
				}
			}

		};
		return defaultlistener;
	}

	/**
	 * @param mode 执行操作的模式，1为发送RPC后还有其它操作，0为不进行其它操作
	 */
	private void insertFines(int mode) {
		String fines = finesNum.getRawValue();
		if (!fines.equals("")) {
			String extSql = "insert hr_salary_ext(multiple, code, createdate, amount, adddate, bcode) " +
			"values(1, 'D06', getdate()," + fines + ",'" + date.getRawValue() + "','" + bcode + "')";
			returnBookSql = returnBookSql.substring(0, returnBookSql.indexOf("fines = ")) + "fines = " + fines + returnBookSql.substring(returnBookSql.indexOf("where") - 1);
			csql.getV().add(extSql);
		}
		csql.getV().add(returnBookSql);
		Separation(csql, mode);
	}
	
	private void insertFines() {
		insertFines(0);
	}
	
	/**
	 * print页面上的内容，页面不做显示，使用于直接PRINT的场合
	 *//*
	private void print() {
		PrintBcodeDialog printdialog = new PrintBcodeDialog("hr_Jsp/finesPrint.jsp?icode="+icode, 1024, 768) ;
		printdialog.show();	
		printdialog.print();
		printdialog.d.hide();
	}*/

	ArrayList<BaseStore> refresh_list = new ArrayList<BaseStore>();

	void Separation(CommandSyncsql comsql, final int model) {
		if (csql.getV().size() > 0) {
			GreetingServiceAsync greetingService = GWT
					.create(GreetingService.class);
			CommandSyncContainer list = new CommandSyncContainer();
			list.add(csql);
			greetingService.SendCommandSync(list,
					new AsyncCallback<CommandSyncReturnObject>() {
						@Override
						public void onFailure(Throwable caught) {
							MessageBox.alert("错误", "网络连接失败", null);
						}

						@Override
						public void onSuccess(CommandSyncReturnObject result) {
							if (result.isB()) {
								grid.getStore().reload();
								borrowBcode.setValue(null);
								book.setValue(null);
								((BaseStore<BaseObject>)borrowBcode.getStore()).reload();
								((BaseStore<BaseObject>)book.getStore()).reload();
								((BaseStore<BaseObject>)searchBcode.getStore()).reload();
								((BaseStore<BaseObject>)searchBook.getStore()).reload();
								csql.getV().clear();
								
								if (model == 1) {
									Window.open(GWT.getHostPageBaseURL() + "hr_Jsp/finesPrint.jsp?icode="+icode,"_blank","menubar=yes,location=yes,resizable=yes,scrollbars=yes,status=yes");
								}
								Info.display("提示", "借出/归还图书成功!");
							} else {
								MessageBox.alert("错误", "错误，错误代码"
										+ result.getMessage(), null);

							}
						}
					});
		}
	}

	void Separation(CommandSyncsql comsql) {
		Separation(comsql, 0);
	}
}
